package org.elzat.healthboxgatewayapp.service.implV1;

import lombok.extern.slf4j.Slf4j;
import org.elzat.healthboxgatewayapp.dto.HealthBoxUser;
import org.elzat.healthboxgatewayapp.dto.HealthBoxUserEntity;
import org.elzat.healthboxgatewayapp.repository.HealthBoxUserRepository;
import org.elzat.healthboxgatewayapp.service.HealthBoxUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Optional;


@Component
@Slf4j
public class HealthBoxUserDetailServiceV1 implements HealthBoxUserDetailsService {
    private final HealthBoxUserRepository userRepo;

    public HealthBoxUserDetailServiceV1(HealthBoxUserRepository userRepo) {
        this.userRepo = userRepo;
    }

    @Override
    public Mono<UserDetails> findByUsername(String username) throws UsernameNotFoundException {
        log.info("user logging in with phone number: " + username);
        log.info("finding user with phone number: " + username);
        Optional<HealthBoxUserEntity> maybe = userRepo.findByUserPhone(username);
        if (!maybe.isPresent())
            return Mono.error(
                    new UsernameNotFoundException("phone number " + username + " not found")
            );
        HealthBoxUserEntity entity = maybe.get();
        log.info("found user: " + entity);
        return Mono.just(HealthBoxUser.fromEntity(entity));
    }
}
